var eb;
var images;

window.onload = function init() {
    eb = new EventBus(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/eventbus');

    eb.onopen = function () {

        // Get the static data
        eb.send('vtoons.listImages', {"category": get("category")}, function (err, reply) {
            if (err) {
                console.error('Failed to retrieve images: ' + err);
                return;
            }
            images = reply.body;
            showImage(images[0]);
        });
    };

    eb.onclose = function () {
        eb = null;
    };

    document.getElementById("prev-btn").addEventListener("click", showPrevImage);
    document.getElementById("next-btn").addEventListener("click", showNextImage);
};

function get(name) {
    if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
        return decodeURIComponent(name[1]);
}

function showImage(image) {
    images.currentImage = image;
    var imageBlock = document.getElementsByClassName("image-block")[0];
    imageBlock.children[0].setAttribute("src", "");

    var downloadingImage = new Image();
    downloadingImage.onload = function () {
        imageBlock.children[0].setAttribute("src", image.imageSrc);
    };
    downloadingImage.src = image.imageSrc;

    var imageTextBlock = document.getElementsByClassName("title-text")[0];
    imageTextBlock.replaceChild(document.createTextNode(image.imageText), imageTextBlock.lastChild);
}

function showPrevImage() {
    var currentImageIndex = images.indexOf(images.currentImage);
    if (currentImageIndex > 0) {
        currentImageIndex--;
        showImage(images[currentImageIndex]);
    }
}

function showNextImage() {
    var currentImageIndex = images.indexOf(images.currentImage);
    if (currentImageIndex < images.length - 1) {
        currentImageIndex++;
        showImage(images[currentImageIndex]);
    }
}
